package akinator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import jpl.Query;

public class BandAkinator extends Thread {

    private List<String> bands, guitarrists, bassists, drummers, vocalists,
            decades, possibilities, albums, countries, styles;
    private List<String> guitarristQuestions, bassistQuestions, drummerQuestions,
            vocalistQuestions, decadeQuestions, albumQuestions, countryQuestions,
            styleQuestions, placesQuestions, diverseQuestions, category;
    private List<String> tempAlbumQuestionList, tempBassistQuestionList,
            tempCountryQuestionList, tempDecadeQuestionList, tempDrummerQuestionList,
            tempGuitarristQuestionList, tempStyleQuestionList, tempVocalistQuestionList,
            tempPlaceQuestionList, tempDiverseQuestionList;
    private int questionWeight;
    private GUI userInterface;
    private boolean rebuild = false, askedMudanca = false, askedBrazil = false,
            askedPernambuco = false, askedRockInRio = false, askedGuitarHero = false,
            askedCountry = false, askedStyle = false, askedDecade = false, askedDrummer = false,
            askedBassist = false, askedGuitarrist = false, askedVocalist = false, askedAlbum = false;

    public BandAkinator(GUI gui) {
        //Escolhe o arquivo com o código prolog
        Query query = new Query("consult('bandas.pl')");

        if (!query.hasSolution()) {
            System.out.println("Erro em: consult('bandas.pl')");
            System.exit(1);
        }
        //instancia listas
        tempAlbumQuestionList = new ArrayList<String>();
        tempBassistQuestionList = new ArrayList<String>();
        tempCountryQuestionList = new ArrayList<String>();
        tempDecadeQuestionList = new ArrayList<String>();
        tempDrummerQuestionList = new ArrayList<String>();
        tempGuitarristQuestionList = new ArrayList<String>();
        tempStyleQuestionList = new ArrayList<String>();
        tempVocalistQuestionList = new ArrayList<String>();
        tempPlaceQuestionList = new ArrayList<String>();
        tempDiverseQuestionList = new ArrayList<String>();

        userInterface = gui;
        //insere elementos nas listas
        initializeLists();
        //insere perguntas
        initializeQuestions();
//        routine();

    }

    @Override
    public void run() {
        routine();
    }
    //Remove aspas da string
    private String removeQuotes(String original) {
        String temp = original.replace("'", "");
        return temp;
    }
    //Retorna uma lista com todas as bandas existentes no código em prolog
    public List<String> getAllBands() {

        Query q = new Query("banda(X).");
        String band;
        List<String> bandList = new ArrayList<String>();

        while (q.hasMoreSolutions()) {
            band = q.nextSolution().get("X").toString();
            bandList.add(band);
        }

        Collections.sort(bandList);
        return bandList;

    }
    //Retorna uma lista com os vocalistas de todas as bandas cadastradas
    public List<String> getAllVocalists() {

        Query q = new Query("vocalista(_,X).");
        String vocalist;
        List<String> vocalistList = new ArrayList<String>();

        while (q.hasMoreSolutions()) {

            vocalist = q.nextSolution().get("X").toString();
            vocalist = removeQuotes(vocalist);

            if (!vocalistList.contains(vocalist)) {
                vocalistList.add(vocalist);
            }
        }

        Collections.sort(vocalistList);
        return vocalistList;

    }
    //Retorna uma lista com os guitarristas de todas as bandas cadastradas
    public List<String> getAllGuitarrists() {

        Query q = new Query("guitarristas(_,X).");
        String guitarrist;
        List<String> guitarristList = new ArrayList<String>();

        while (q.hasMoreSolutions()) {

            guitarrist = q.nextSolution().get("X").toString();
            guitarrist = removeQuotes(guitarrist);

            if (!guitarristList.contains(guitarrist)) {
                guitarristList.add(guitarrist);
            }
        }

        Collections.sort(guitarristList);
        return guitarristList;

    }
    //Retorna uma lista com os bateristas de todas as bandas cadastradas
    public List<String> getAllDrummers() {

        Query q = new Query("baterista(_,X).");
        String drummer;
        List<String> drummerList = new ArrayList<String>();

        while (q.hasMoreSolutions()) {

            drummer = q.nextSolution().get("X").toString();
            drummer = removeQuotes(drummer);

            if (!drummerList.contains(drummer)) {
                drummerList.add(drummer);
            }
        }

        Collections.sort(drummerList);
        return drummerList;

    }
    //Retorna uma lista com os baixistas de todas as bandas cadastradas
    public List<String> getAllBassists() {

        Query q = new Query("baixista(_,X).");
        String bassist;
        List<String> bassistList = new ArrayList<String>();

        while (q.hasMoreSolutions()) {

            bassist = q.nextSolution().get("X").toString();
            bassist = removeQuotes(bassist);

            if (!bassistList.contains(bassist)) {
                bassistList.add(bassist);
            }
        }

        Collections.sort(bassistList);
        return bassistList;

    }
    //Retorna uma lista com as vocalistas de todas as bandas cadastradas
    public List<String> getAllDecades() {

        Query q = new Query("decada(_,X).");
        String decade;
        List<String> decadeList = new ArrayList<String>();

        while (q.hasMoreSolutions()) {

            decade = q.nextSolution().get("X").toString();
            decade = removeQuotes(decade);

            if (!decadeList.contains(decade)) {
                decadeList.add(decade);
            }
        }

        Collections.sort(decadeList);
        return decadeList;

    }
    //Retorna uma lista com 1 álbum de cada banda cadastrada
    public List<String> getAllAlbums() {

        Query q = new Query("albumPrincipal(_,X).");
        String album;
        List<String> albumList = new ArrayList<String>();

        while (q.hasMoreSolutions()) {

            album = q.nextSolution().get("X").toString();
            album = removeQuotes(album);

            if (!albumList.contains(album)) {
                albumList.add(album);
            }
        }

        Collections.sort(albumList);
        return albumList;

    }
    //Retorna uma lista com os países de todas as bandas cadastradas
    public List<String> getAllCountries() {

        Query q = new Query("pais(_,X).");
        String country;
        List<String> countryList = new ArrayList<String>();

        while (q.hasMoreSolutions()) {

            country = q.nextSolution().get("X").toString();
            country = removeQuotes(country);

            if (!countryList.contains(country)) {
                countryList.add(country);
            }
        }

        Collections.sort(countryList);
        return countryList;

    }
    //Retorna uma lista com os estilos de todas as bandas cadastradas
    public List<String> getAllStyles() {

        Query q = new Query("estilo(_,X).");
        String decade;
        List<String> decadeList = new ArrayList<String>();

        while (q.hasMoreSolutions()) {

            decade = q.nextSolution().get("X").toString();
            decade = removeQuotes(decade);

            if (!decadeList.contains(decade)) {
                decadeList.add(decade);
            }
        }

        Collections.sort(decadeList);
        return decadeList;

    }

    //Insere os valores nas listas
    public void initializeLists() {
        this.albums = getAllAlbums();
        this.bands = getAllBands();
        this.bassists = getAllBassists();
        this.countries = getAllCountries();
        this.decades = getAllDecades();
        this.drummers = getAllDrummers();
        this.guitarrists = getAllGuitarrists();
        this.styles = getAllStyles();
        this.vocalists = getAllVocalists();
    }

    //Cria todas as perguntas
    public void initializeQuestions() {

        albumQuestions = new ArrayList<String>();
        for (String album : albums) {
            albumQuestions.add("A banda escolhida possui o álbum \"" + album + "\"?");
        }

        bassistQuestions = new ArrayList<String>();
        for (String bassist : bassists) {
            bassistQuestions.add("O(a) baixista \"" + bassist + "\" está na banda?");
        }

        countryQuestions = new ArrayList<String>();
        for (String country : countries) {
            countryQuestions.add("Esta banda foi formada em " + country + "?");
        }

        decadeQuestions = new ArrayList<String>();
        for (String decade : decades) {
            decadeQuestions.add("Esta banda foi formada na década de " + decade + "?");
        }

        drummerQuestions = new ArrayList<String>();
        for (String drummer : drummers) {
            drummerQuestions.add("O(a) baterista \"" + drummer + "\" faz parte desta banda?");
        }

        guitarristQuestions = new ArrayList<String>();
        for (String guitarrist : guitarrists) {
            guitarristQuestions.add("Guitarrista(s) \"" + guitarrist + "\" é(são) integrante(s) desta banda?");
        }

        styleQuestions = new ArrayList<String>();
        for (String style : styles) {
            styleQuestions.add("A banda é conhecida pelo gênero musical \"" + style + "\"?");
        }

        vocalistQuestions = new ArrayList<String>();
        for (String vocalist : vocalists) {
            vocalistQuestions.add("O(a) vocalista \"" + vocalist + "\" faz parte da banda?");
        }

        placesQuestions = new ArrayList<String>();
        placesQuestions.add("A banda escolhida já tocou no Brasil?");
        placesQuestions.add("A banda escolhida já tocou no RockInRio?");
        placesQuestions.add("A banda escolhida já tocou em Pernambuco?");

        diverseQuestions = new ArrayList<String>();
        diverseQuestions.add("A banda escolhida possui alguma de suas músicas disponível em algum Guitar Hero?");
        diverseQuestions.add("A banda escolhida já mudou sua formação em algum momento de existência?");

        category = new ArrayList<String>();
        category.add("Albums");
        category.add("Bassists");
        category.add("Countries");
        category.add("Decades");
        category.add("Drummers");
        category.add("Guitarrists");
        category.add("Styles");
        category.add("Vocalists");
        category.add("Places");
        category.add("Diverse");

        possibilities = new ArrayList<String>();
        for (String possibility : bands) {
            possibilities.add(removeQuotes(possibility));
        }

    }

    //Retorna true se a banda deve permanecer na lista de resultados possíveis, e false caso contrário
    public boolean isCorrect(String param, String result, boolean equals) {
        //remove as aspas e deixa ignora o case sensitive
        param = removeQuotes(param).toLowerCase();
        result = removeQuotes(result).toLowerCase();
        boolean r = false;
        //Testa se deveriam ser iguais
        if (equals) {
            //testa se são iguais
            if (result == null ? param == null : result.equals(param)) {
                r = true;
            }
        } else {
            //testa se são diferentes
            if (result == null ? param != null : !result.equals(param)) {
                r = true;
            }
        }

        return r;
    }

    //Pergunta se um vocalista está na banda
    public void makeVocalistQuestionWait() {

        if (!askedVocalist) {

            if (vocalistQuestions.isEmpty()) {
                return;
            }

            int random = (int) (Math.random() * vocalistQuestions.size());

            putQuestion(vocalistQuestions.get(random));
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeVocalistQuestionVerify(random, userInterface.getDecision());

        }

    }

    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeVocalistQuestionVerify(int random, int response) {

        if (response == 0) {
            askedVocalist = true;
            for (String band : bands) {

                Query q = new Query("vocalista(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!isCorrect(vocalists.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        } else {

            for (String band : bands) {

                Query q = new Query("vocalista(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (isCorrect(vocalists.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));


                    }
                } else {
                    System.out.println("sem solução");
                }
            }

            vocalists.remove(random);

        }

        vocalistQuestions.remove(random);
        tryToGuess();

    }

    //Pergunta se um guitarrista está na banda
    public void makeGuitarristQuestionWait() {

        if (!askedGuitarrist) {

            if (guitarristQuestions.isEmpty()) {
                return;
            }

            int random = (int) (Math.random() * guitarristQuestions.size());

            putQuestion(guitarristQuestions.get(random));
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeGuitarristQuestionVerify(random, userInterface.getDecision());

        }

    }

    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeGuitarristQuestionVerify(int random, int response) {

        if (response == 0) {
            askedGuitarrist = true;
            for (String band : bands) {

                Query q = new Query("guitarristas(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!isCorrect(guitarrists.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        } else {

            for (String band : bands) {

                Query q = new Query("guitarristas(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (isCorrect(guitarrists.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));


                    }
                } else {
                    System.out.println("sem solução");
                }
            }

            guitarrists.remove(random);

        }

        guitarristQuestions.remove(random);
        tryToGuess();

    }

    //Pergunta se um baixista está na banda
    public void makeBassistQuestionWait() {

        if (!askedBassist) {

            if (bassistQuestions.isEmpty()) {
                return;
            }

            int random = (int) (Math.random() * bassistQuestions.size());

            putQuestion(bassistQuestions.get(random));
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeBassistQuestionVerify(random, userInterface.getDecision());

        }

    }
    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeBassistQuestionVerify(int random, int response) {

        if (response == 0) {
            askedBassist = true;
            for (String band : bands) {

                Query q = new Query("baixista(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!isCorrect(bassists.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        } else {

            for (String band : bands) {

                Query q = new Query("baixista(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (isCorrect(bassists.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));


                    }
                } else {
                    System.out.println("sem solução");
                }
            }

            bassists.remove(random);

        }

        bassistQuestions.remove(random);
        tryToGuess();

    }
    //Pergunta se um baterista está na banda
    public void makeDrummerQuestionWait() {

        if (!askedDrummer) {

            if (drummerQuestions.isEmpty()) {
                return;
            }

            int random = (int) (Math.random() * drummerQuestions.size());

            putQuestion(drummerQuestions.get(random));
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeDrummerQuestionVerify(random, userInterface.getDecision());

        }

    }
    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeDrummerQuestionVerify(int random, int response) {

        if (response == 0) {
            askedDrummer = true;
            for (String band : bands) {

                Query q = new Query("baterista(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!isCorrect(drummers.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        } else {

            for (String band : bands) {

                Query q = new Query("baixista(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (isCorrect(drummers.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));


                    }
                } else {
                    System.out.println("sem solução");
                }
            }

            drummers.remove(random);

        }

        drummerQuestions.remove(random);
        tryToGuess();

    }
    //Pergunta se a banda é de determinado país
    public void makeCountryQuestionWait() {

        if (!askedCountry) {

            if (countryQuestions.isEmpty()) {
                return;
            }

            int random = (int) (Math.random() * countryQuestions.size());

            putQuestion(countryQuestions.get(random));
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeCountryQuestionVerify(random, userInterface.getDecision());

        }

    }

    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeCountryQuestionVerify(int random, int response) {

        if (response == 0) {
            askedCountry = true;
            for (String band : bands) {

                Query q = new Query("pais(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!isCorrect(countries.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }

        } else {

            for (String band : bands) {

                Query q = new Query("pais(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (isCorrect(countries.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }

            countries.remove(random);

        }

        countryQuestions.remove(random);
        tryToGuess();

    }

    //Exibe a pergunta na GUI
    public void putQuestion(String question) {

        if (question.length() > 40) {
            String temp1, temp2;
            temp1 = question.substring(0, 39);
            temp2 = question.substring(39, question.length());
            userInterface.getLine2().setText("  " + temp1);
            userInterface.getLine3().setText("  " + temp2);
        } else {
            userInterface.getLine2().setText("  " + question);
            userInterface.getLine3().setText("");
        }
    }

    public void makeDecadeQuestionWait() {

        if (!askedDecade) {

            if (decadeQuestions.isEmpty()) {
                return;
            }

            int random = (int) (Math.random() * decadeQuestions.size());

            putQuestion(decadeQuestions.get(random));
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeDecadeQuestionVerify(random, userInterface.getDecision());

        }

    }
    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeDecadeQuestionVerify(int random, int response) {

        //System.out.println("Random: " + random);
        //System.out.println("Decision: " + response);

        if (response == 0) {
            askedDecade = true;
            for (String band : bands) {

                Query q = new Query("decada(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!isCorrect(decades.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        } else {
            for (String band : bands) {

                Query q = new Query("decada(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (isCorrect(decades.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }

            decades.remove(random);

        }

        decadeQuestions.remove(random);
        tryToGuess();
//        }
    }
    //Pergunta se a banda é de determinado estilo
    public void makeStyleQuestionWait() {

        if (!askedStyle) {

            if (styleQuestions.isEmpty()) {
                return;
            }

            int random = (int) (Math.random() * styleQuestions.size());

            putQuestion(styleQuestions.get(random));
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeStyleQuestionVerify(random, userInterface.getDecision());

        }

    }
    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeStyleQuestionVerify(int random, int response) {

        if (response == 0) {
            askedStyle = true;
            for (String band : bands) {

                Query q = new Query("estilo(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!isCorrect(styles.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        } else {

            for (String band : bands) {

                Query q = new Query("estilo(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (isCorrect(styles.get(random), result, true)) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }

            styles.remove(random);

        }

        styleQuestions.remove(random);
        tryToGuess();

    }
    //Pergunta se a banda ja mudou a sua formação
    public void makeFormationQuestionWait() {

        if (!askedMudanca) {

            putQuestion("A banda escolhida já mudou sua formação em algum momento de existência?");
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeFormationQuestionVerify(userInterface.getDecision());

        }

    }
    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeFormationQuestionVerify(int response) {

        if (response == 0) {

            for (String band : bands) {

                Query q = new Query("mudouFormacao(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();

                    if (!removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }

            }
        } else {

            for (String band : bands) {

                Query q = new Query("mudouFormacao(\'" + removeQuotes(band) + "\', X).");


                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();

                    if (removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }

                } else {
                    System.out.println("sem solução");
                }
            }

        }

        askedMudanca = true;
        tryToGuess();

    }
    //Pergunta se a banda ja tocou no Brasil
    public void makePlayedBrazilQuestionWait() {

        if (!askedBrazil) {

            putQuestion("A banda escolhida já se apresentou no  Brasil?");
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makePlayedBrazilQuestionVerify(userInterface.getDecision());

        }

    }
    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makePlayedBrazilQuestionVerify(int response) {

        if (response == 0) {

            for (String band : bands) {

                Query q = new Query("tocouBrasil(\'" + removeQuotes(band) + "\', X).");
                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }

            }
        } else {//NAO

            for (String band : bands) {

                Query q = new Query("tocouBrasil(\'" + removeQuotes(band) + "\', X).");
                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        }

        askedBrazil = true;
        tryToGuess();

    }
    //Pergunta se a banda ja tocou em Pernambuco
    public void makePlayedPernambucoQuestionWait() {

        if (!askedPernambuco) {

            putQuestion("A banda escolhida já se apresentou em  Pernambuco?");
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makePlayedPernambucoQuestionVerify(userInterface.getDecision());

        }

    }
    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makePlayedPernambucoQuestionVerify(int response) {

        if (response == 0) {

            for (String band : bands) {

                Query q = new Query("tocouPernambuco(\'" + removeQuotes(band) + "\', X).");
                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }

            }
        } else {//NAO

            for (String band : bands) {

                Query q = new Query("tocouPernambuco(\'" + removeQuotes(band) + "\', X).");
                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        }
        askedPernambuco = true;
        tryToGuess();
    }
    //Pergunta se a banda ja tocou no Rock in Rio (No Rio)
    public void makeRockInRioQuestionWait() {

        if (!askedRockInRio) {

            putQuestion("A banda escolhida já se apresentou no  Rock in Rio (No Rio de Janeiro)?");
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeRockInRioQuestionVerify(userInterface.getDecision());

        }

    }
    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeRockInRioQuestionVerify(int response) {

        if (response == 0) {

            for (String band : bands) {

                Query q = new Query("tocouRockInRio(\'" + removeQuotes(band) + "\', X).");
                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }

            }
        } else {//NAO

            for (String band : bands) {

                Query q = new Query("tocouRockInRio(\'" + removeQuotes(band) + "\', X).");
                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        }

        askedRockInRio = true;
        tryToGuess();

    }
    //Pergunta se a banda tem alguma música numa versão oficial do Guitar Hero
    public void makeGuitarHeroQuestionWait() {

        if (!askedGuitarHero) {

            putQuestion("A banda escolhida tem alguma música em alguma edição oficial do \"Guitar Hero\"?");
            userInterface.setCanChoose(true);

            while (userInterface.isCanChoose()) {

                if (!userInterface.isCanChoose()) {
                    break;
                }

                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    Logger.getLogger(BandAkinator.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

            makeGuitarHeroQuestionVerify(userInterface.getDecision());

        }

    }
    //Remove as bandas que foram eliminadas de acordo com a resposta do usuário
    public void makeGuitarHeroQuestionVerify(int response) {

        if (response == 0) {

            for (String band : bands) {

                Query q = new Query("guitarHero(\'" + removeQuotes(band) + "\', X).");
                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (!removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }

            }
        } else {//NAO

            for (String band : bands) {

                Query q = new Query("guitarHero(\'" + removeQuotes(band) + "\', X).");
                if (q.hasSolution()) {
                    String result = q.oneSolution().get("X").toString();
                    if (removeQuotes(result).equalsIgnoreCase("true")) {
                        possibilities.remove(removeQuotes(band));
                    }
                } else {
                    System.out.println("sem solução");
                }
            }
        }
        askedGuitarHero = true;
        tryToGuess();

    }

    //Tenta adivinhar a banda
    public void tryToGuess() {
        //Só adivinha a banda se a quantidade de possibilidade for igual a 1, se for 0 não conseguiu adivinhar
        if (possibilities.size() == 1) {
            try {
                JFrame answer = new GuessGUI(possibilities.get(0).toUpperCase(), "./img/" + possibilities.get(0) + ".png");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "A banda é \"" + possibilities.get(0).toUpperCase() + "\"");
            }

            //System.exit(0);
        } else if (possibilities.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Não consegui descobrir a banda");
            System.exit(0);
        }

    }

    //Faz as perguntas escolhendo a categoria aleatoriamente
    public void routine() {
        
        int random = (int) (Math.random() * category.size());

        while (possibilities.size() > 1) {
            random = (int) (Math.random() * (category.size() + 1));

            switch (random) {

                case 0:
                    if (!askedDecade) {
                        makeDecadeQuestionWait();
                    }
                    break;
                case 1:
                    if (!askedGuitarHero) {
                        makeGuitarHeroQuestionWait();
                    }
                    break;
                case 2:
                    if (!askedMudanca) {
                        makeFormationQuestionWait();
                    }
                    break;
                case 3:
                    if (!askedBrazil) {
                        makePlayedBrazilQuestionWait();
                    }
                    break;
                case 4:
                    if (!askedRockInRio) {
                        makeRockInRioQuestionWait();
                    }
                    break;
                case 5:
                    if (!askedPernambuco) {
                        makePlayedPernambucoQuestionWait();
                    }
                    break;
                case 6:
                    if (!askedStyle) {
                        makeStyleQuestionWait();
                    }
                    break;
                case 7:
                    if (!askedCountry) {
                        makeCountryQuestionWait();
                    }
                    break;
                case 8:
                    if (!askedVocalist) {
                        makeVocalistQuestionWait();
                    }
                    break;
                case 9:
                    if (!askedBassist) {
                        makeBassistQuestionWait();
                    }
                    break;
                case 10:
                    if (!askedGuitarrist) {
                        makeGuitarristQuestionWait();
                    }
                    break;
                case 11:
                    if (!askedDrummer) {
                        makeDrummerQuestionWait();
                    }
                    break;

            }
            userInterface.updateCount();
        }
    }
}
